import pyglet
from pyglet.window import key
from pyglet.gl import *
from Mobile import Mobile
import UI
import CAConfig
from Util import constrain

class State:
    """
    Handle states for the Hero
    """
    dialog = False
    collections = False

class Hero(Mobile):
    
    def __init__(self, *args, **kwargs):
        Mobile.__init__(self, *args)
        self.state = State()
        # axis,velocity multiplier
        self.velocity_map = {
            key.UP: (1,1),
            key.DOWN: (1,-1),
            key.LEFT: (0,-1),
            key.RIGHT: (0,1)
        }
    
    # This section needs to be generalized for toggleable ui components
    def on_key_press(self,symbol,modifiers):
        # movement
        k = self.velocity_map.get(symbol)
        if k:
            axis,velocity = k
            velocity = velocity * self.acceleration
            self.set_velocity(axis,velocity)
        # action
        elif symbol == key.SPACE:
            if not self.state.dialog:
                self.window.ui['dialog'] = UI.Dialog(message="There is nothing for you to interact with yet. Sorry...")
                self.state.dialog = True
            else:
                del self.window.ui['dialog']
                self.state.dialog = False
        elif symbol == key.C:
            if not self.state.collections:
                self.window.ui['collections'] = UI.Collections()
                self.state.collections = True
            else:
                del self.window.ui['collections']
                self.state.collections = False
    
    # reverse the velocity to handle 'turning off' acceleration
    def on_key_release(self,symbol,modifiers):
        k = self.velocity_map.get(symbol)
        if k:
            axis,velocity = k
            velocity = velocity * self.acceleration
            self.set_velocity(axis,-velocity)
    
    def update(self):
        if self.velocity[0] != 0 or self.velocity[1] != 0:
            self.update_direction()
            self.move()
        return self.get_scroll()
    
    def get_scroll(self):
        max_x,max_y = CAConfig.map_size
        view_x,view_y = CAConfig.window.viewport
        center_x,center_y = self.get_center()
        x = center_x - view_x/2
        y = center_y - view_y/2
        max_allowable_x = max_x - view_x
        max_allowable_y = max_y - view_y
        return (constrain(x,0,max_allowable_x),constrain(y,0,max_allowable_y))
